package com.heba.greenmulu.diary;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.user.UserObject;
import com.heba.config.CommonConfig;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.businesslist.BusinessHomePageActivity;
import com.heba.greenmulu.businesslist.BusinessPersonActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.view.RoundImageView;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 點讚列表
 * Created by jason on 2020/5/18.
 */
public class ItemDiaryLikeListActivity extends BaseActivity {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private List<UserObject> list;

    private String diaryID;
    private int likeCount;   //點讚數量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recyclerview);
        initTopbar();
        findViewById();
        initView();
        getLikeListData();
    }

    @Override
    protected void findViewById() {
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recyclerView);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            diaryID = bundle.getString(CommonConfig.DIARY_ID, "");
            likeCount = bundle.getInt(CommonConfig.LIKE_COUNT, 0);
        }

        txt_title.setText(String.format(getResources().getString(R.string.diary_like_count), likeCount));

        list = new ArrayList<>();

        recycleAdapter = new QuickAdapter<UserObject>(list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_follow_row;
            }

            @Override
            public void convert(VH holder, UserObject data, int position) {
                RoundImageView imageView = holder.getView(R.id.img_avatar);
                TextView txt_follow = holder.getView(R.id.txt_follow);
                holder.setText(R.id.txt_name, data.getAccount());
                holder.setText(R.id.txt_desc, data.getNickname());

                /**
                 * 判断用户的关注情况
                 */
                txt_follow.setVisibility(View.VISIBLE);
                txt_follow.setEnabled(false);
                switch (Integer.valueOf(data.getStatus())) {
                    case 0:
                        //互相关注
                        txt_follow.setEnabled(false);
                        txt_follow.setCompoundDrawables(null, null, null, null);
                        txt_follow.setText(ItemDiaryLikeListActivity.this.getResources().getString(R.string.mine_focus1));
                        break;
                    case 1:
                        //已关注
                        txt_follow.setEnabled(false);
                        txt_follow.setCompoundDrawables(null, null, null, null);
                        txt_follow.setText(ItemDiaryLikeListActivity.this.getResources().getString(R.string.mine_focus2));
                        break;
                    case 2:
                        //未关注
                        txt_follow.setEnabled(true);
                        Drawable left = getResources().getDrawable(R.drawable.icon_diary_focus_on, null);
                        left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
                        txt_follow.setCompoundDrawablePadding(DensityUtils.dip2px(ItemDiaryLikeListActivity.this, 4));
                        txt_follow.setCompoundDrawables(left, null, null, null);
                        txt_follow.setText(ItemDiaryLikeListActivity.this.getResources().getString(R.string.mine_focus));
                        break;
                    default:
                        txt_follow.setVisibility(View.INVISIBLE);
                        break;
                }

                //显示头像
                GlideUtil.loadImageWithPlaceHolderID(ItemDiaryLikeListActivity.this, data.getIcon(), imageView, R.drawable.icon_head_portrait);

                /**
                 * 关注用户
                 */
                txt_follow.setOnClickListener(v -> {
                    loading.Start();
                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                        @Override
                        public void Success() {
                            loading.End();
                            data.setStatus(String.valueOf(1));
                            notifyItemChanged(position);
                        }

                        @Override
                        public void Fail(String error) {
                            loading.End();
                        }
                    }).followUser(ItemDiaryLikeListActivity.this, data.getUserID());
                });

                /**
                 * 查看用户主页
                 */
                holder.itemView.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.SEND_USER_ID, data.getUserID());
                    if (data.getAccountType() == 0){
                        openActivity(ItemPersonHomePageActivity.class, bundle);
                    }else{
                        openActivity(BusinessPersonActivity.class, bundle);
                    }
                });
            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            Page = 1;
            isRefreshFromTop = true;
            getLikeListData();
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Page++;
            isRefreshFromTop = false;
            getLikeListData();
        });
    }

    /**
     * 獲取點讚列表數據
     */
    private void getLikeListData() {
        if (firstRefresh) {
            progressDialog.show();
            firstRefresh = false;
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", PerPage);
        params.put("DiaryID", diaryID);
        client.get(Cfg.BaseUrl + "/Diary/LikeList", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);

                        /**
                         * 下拉刷新处理
                         */
                        if (isRefreshFromTop) {
                            isRefreshFromTop = false;
                            refreshLayout.setNoMoreData(false);
                            list.clear();
                        }

                        try {
                            JSONObject ob = new JSONObject(response.trim()).getJSONObject("Result");
                            JSONArray jsonArray = ob.getJSONArray("LikeList");
                            if (jsonArray.length() > 0) {
                                List<UserObject> userObjects = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<UserObject>>() {
                                }.getType());
                                list.addAll(list.size(), userObjects);
                            } else {
                                //无数据
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //刷新数据
                        recycleAdapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);
                    }

                });
    }
}
